﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SCClock {


    private double pts;
    private double pts_drift;
    private double last_updated;
    private bool paused;

    private const int AV_NOSYNC_THRESHOLD = 25;

    public SCClock()
    {
        SetClock(double.NaN);
        paused = false;
    }

    public void SetClock(double crtts)
    {
        //utc 时间戳
        double time = IStreamCapture.GetTimestampUTC() / 1000.0;
        SetClockAt(crtts, time);
    }

    public void SetClockAt(double pts, double time)
    {
        this.pts = pts;
        this.last_updated = time;
        this.pts_drift = pts - time;
        //double dt = IStreamCapture.GetTimestampUTC() / 1000.0 + pts_drift;
    }

    public double GetClock()
    {
        if (paused)
        {
            return pts;
        }
        else
        {
            double time = IStreamCapture.GetTimestampUTC() / 1000.0;
            double d = pts_drift + time;
            return pts_drift + time;
        }
    }

    public void SyncClockToSlave(SCClock slave, bool force)
    {
        double clock = GetClock();
        double slave_clock = slave.GetClock();
        if (!double.IsNaN(slave_clock) && (double.IsNaN(clock) || Mathf.Abs((float)(clock - slave_clock)) > AV_NOSYNC_THRESHOLD) || force)
        {
            SetClock(slave_clock);
        }
    }
}
